

<!DOCTYPE html>
<html lang="zh" xmlns:v-bind="http://www.w3.org/1999/xhtml">

<head><meta name="generator" content="Hexo 3.9.0">
    <title>Go Web Server上传文件实践 - suke`s Notice</title>
<meta charset="utf-8">
<meta name="X-UA-Compatible" content="IE=edge">
<meta name="author" content="suke">
<meta name="description" content="
https://github.com/Treblex/go-echo-demo/blob/master/serv...">
<meta name="keywords" content="javascript html css php server npm nodejs">

<link rel="alternate" type="application/atom+xml" title="ATOM 1.0" href="/atom.xml">

    <meta charset="utf-8">
    <meta name="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta content="telephone=no" name="format-detection">
    <meta name="renderer" content="webkit">
    <meta name="theme-color" content="#ffffff">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css" integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE=" crossorigin="anonymous">
<link rel="stylesheet" href="/css/journal.css?56833581">

<script src="/js/loadCSS.js"></script>
<script>
    loadCSS("https://fonts.googleapis.com/css?family=Lora|Montserrat|Fira+Mono|Material+Icons");
    (function (d) {
        var config = {
                kitId: 'dwg1tuc',
                scriptTimeout: 3000,
                async: true
            },
            h = d.documentElement, t = setTimeout(function () {
                h.className = h.className.replace(/\bwf-loading\b/g, "") + " wf-inactive";
            }, config.scriptTimeout), tk = d.createElement("script"), f = false,
            s = d.getElementsByTagName("script")[0], a;
        h.className += " wf-loading";
        tk.src = 'https://use.typekit.net/' + config.kitId + '.js';
        tk.async = true;
        tk.onload = tk.onreadystatechange = function () {
            a = this.readyState;
            if (f || a && a != "complete" && a != "loaded") return;
            f = true;
            clearTimeout(t);
            try {
                Typekit.load(config)
            } catch (e) {
            }
        };
        s.parentNode.insertBefore(tk, s)
    })(document);
</script>
<noscript>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora|Montserrat|Anonymous+Pro:400|Material+Icons">
</noscript>
</head>
<body>
<div id="top"></div>
<div id="app">
<div class="single-column-drawer-container" ref="drawer" v-bind:class="{ 'single-column-drawer-container-active': isDrawerOpen }">
    <div class="drawer-content">
        <div class="drawer-menu">
            <a class="a-block drawer-menu-item false" href="https://sukeai.netlify.com">
                Home
            </a>
            

            
            
            <a class="a-block drawer-menu-item false" href="/firends/index.html">
                朋友👬
            </a>
            
            <a class="a-block drawer-menu-item false" href="/projects/index.html">
                空闲下来做的项目
            </a>
            
            <a class="a-block drawer-menu-item false" href="/about/index.html">
                关于我
            </a>
            

            
            <a class="a-block drawer-menu-item" href="/atom.xml">
                RSS
            </a>
            
        </div>
    </div>
</div>
<transition name="fade">
    <div v-bind:class="{ 'single-column-drawer-mask': mounted }" v-if="isDrawerOpen" v-on:click="toggleDrawer"></div>
</transition>
<nav ref="navBar" class="navbar sticky-top navbar-light single-column-nav-container">
    <div ref="navBackground" class="nav-background"></div>
    <div class="container container-narrow nav-content">
        <button id="nav_dropdown_btn" class="nav-dropdown-toggle" type="button" v-on:click="toggleDrawer">
            <i class="material-icons">
                menu
            </i>
        </button>
        <a ref="navTitle" class="navbar-brand" href="/">
            suke`s Notice
        </a>
    </div>
</nav>
<div class="single-column-header-container" ref="pageHead" v-bind:style="{ transform: 'translateZ(0px) translateY('+.3*scrollY+'px)', opacity: 1-navOpacity }">
    <a href="/">
        <div class="single-column-header-title">suke`s Notice</div>
        <div class="single-column-header-subtitle">hexo博客</div>
    </a>
</div>
<div ref="sideContainer" class="side-container">
    <a class="a-block nav-head false" href="/">
        <div class="nav-title">
            有猫病.
        </div>
        <div class="nav-subtitle">
             她的眼里有光,她爱的人是谁呢 
        </div>
    </a>

    <div class="nav-link-list">
        

        
        
        <a class="a-block nav-link-item false" href="/firends/index.html">
            朋友👬
        </a>
        
        <a class="a-block nav-link-item false" href="/projects/index.html">
            空闲下来做的项目
        </a>
        
        <a class="a-block nav-link-item false" href="/about/index.html">
            关于我
        </a>
        

        
        <a class="a-block no-tint nav-link-item" href="/atom.xml">
            RSS
        </a>
        
    </div>

    
    <div class="nav-footer">
        Proudly published with Hexo<br>
        
        Theme <a href="https://github.com/SumiMakito/hexo-theme-journal/" target="_blank" rel="noreferrer noopener">Journal.</a> by <a href="https://mak1t0.cc/" target="_blank" rel="noreferrer noopener">Makito</a><br>
        
        &copy; 2020 <a href="https://sukeai.netlify.com">suke`s Notice</a>
    </div>
</div>
<div ref="extraContainer" class="extra-container">
    <div class="pagination">
        <a id="globalBackToTop" class="pagination-action animated-visibility" href="#top" :class="{ invisible: scrollY == 0 }">
            <i class="material-icons pagination-action-icon">
                keyboard_arrow_up
            </i>
        </a>

        
    </div>
</div>



<div ref="streamContainer" class="stream-container">
    <div class="post-list-container post-list-container-shadow">
        <div class="post">
            <div class="post-head-wrapper-text-only" style="background-image: url('')">
                <div class="post-title">
                    Go Web Server上传文件实践
                    <div class="post-meta">
                        <time datetime="2020-04-21T15:05:28.000Z" itemprop="datePublished">
                            2020-04-21 15:05
                        </time>&nbsp;
                        
    
                        
                    </div>
                </div>
            </div>
    
            <div class="post-body-wrapper">
                <div class="post-body">
                    <!-- 文件地址 -->
<p><a href="https://github.com/Treblex/go-echo-demo/blob/master/server/router/router.go#L63" target="_blank" rel="noopener">https://github.com/Treblex/go-echo-demo/blob/master/server/router/router.go#L63</a></p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">upload</span><span class="params">(c echo.Context)</span> <span class="title">error</span></span> &#123;</span><br><span class="line">	file, err := c.FormFile(<span class="string">"file"</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> util.JSONErr(c, err, <span class="string">"上传错误"</span>) <span class="comment">//未获取到文件流</span></span><br><span class="line">	&#125;</span><br><span class="line">	pathExt := path.Ext(file.Filename)</span><br><span class="line">	acceptsImgExt := []<span class="keyword">interface</span>&#123;&#125;&#123;<span class="string">"jpg"</span>, <span class="string">"png"</span>, <span class="string">"jpeg"</span>, <span class="string">"webp"</span>&#125;           <span class="comment">//图片类型</span></span><br><span class="line">	acceptsVideoExt := []<span class="keyword">interface</span>&#123;&#125;&#123;<span class="string">"mov"</span>, <span class="string">"mp4"</span>, <span class="string">"avi"</span>&#125;                  <span class="comment">//视频类型</span></span><br><span class="line">	acceptsOtherFileExt := []<span class="keyword">interface</span>&#123;&#125;&#123;<span class="string">"pdf"</span>, <span class="string">"zip"</span>, <span class="string">"rar"</span>, <span class="string">"gz"</span>, <span class="string">"txt"</span>&#125; <span class="comment">//其他文件类型</span></span><br><span class="line">	folder := <span class="string">""</span></span><br><span class="line">	<span class="comment">// 如果符合类型，设定目录</span></span><br><span class="line">	<span class="keyword">if</span> inArray(acceptsImgExt, strings.Trim(pathExt, <span class="string">"."</span>)) &#123;</span><br><span class="line">		folder = <span class="string">"image"</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> inArray(acceptsVideoExt, strings.Trim(pathExt, <span class="string">"."</span>)) &#123;</span><br><span class="line">		folder = <span class="string">"video"</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> inArray(acceptsOtherFileExt, strings.Trim(pathExt, <span class="string">"."</span>)) &#123;</span><br><span class="line">		folder = <span class="string">"file"</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 如果不符合任何一种类型</span></span><br><span class="line">	<span class="keyword">if</span> folder == <span class="string">""</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> util.JSONErr(c, <span class="literal">nil</span>, <span class="string">"文件不合法"</span>)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 打开文件流</span></span><br><span class="line">	src, err := file.Open()</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> util.JSONErr(c, err, <span class="string">"打开文件失败"</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> src.Close() <span class="comment">//函数结束时自动关闭文件</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">//创建文件夹</span></span><br><span class="line">	dir, err := getDir(<span class="string">"./static/upload/"</span>+folder+<span class="string">"/"</span>, time.Now().Format(<span class="string">"2006_01_02"</span>))</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> util.JSONErr(c, err, <span class="string">"创建文件夹失败"</span>)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 随机文件名 + 文件后缀</span></span><br><span class="line">	randName := util.RandStringBytes(<span class="number">32</span>) + pathExt</span><br><span class="line">	<span class="comment">// Destination</span></span><br><span class="line">	fileName := filepath.Join(dir, randName)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 创建空文件</span></span><br><span class="line">	dst, err := os.Create(fileName)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> util.JSONErr(c, err, <span class="string">"创建文件失败"</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> dst.Close()</span><br><span class="line">	<span class="comment">// Copy文件流到新建到文件</span></span><br><span class="line">	<span class="keyword">if</span> _, err = io.Copy(dst, src); err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> util.JSONErr(c, err, <span class="string">"拷贝文件至目标失败"</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 拼接文件地址，不带协议头，方便处理http 到https升级 ， 其实也没找到协议头在哪儿，req对象里没有返回到空字符串</span></span><br><span class="line">	<span class="keyword">return</span> util.JSON(c, fmt.Sprintf(<span class="string">"//%s/%s"</span>, c.Request().Host, fileName), <span class="string">"上传成功"</span>, <span class="number">200</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建文件夹</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getDir</span><span class="params">(path <span class="keyword">string</span>, foderName <span class="keyword">string</span>)</span> <span class="params">(dir <span class="keyword">string</span>, err error)</span></span> &#123;</span><br><span class="line">	folder := filepath.Join(path, foderName)</span><br><span class="line">	<span class="keyword">if</span> _, err = os.Stat(folder); os.IsNotExist(err) &#123;</span><br><span class="line">		err = os.MkdirAll(folder, os.ModePerm)</span><br><span class="line">		<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	dir = folder</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在数组中</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">inArray</span><span class="params">(arr []<span class="keyword">interface</span>&#123;&#125;, item <span class="keyword">interface</span>&#123;&#125;)</span> <span class="params">(inArr <span class="keyword">bool</span>)</span></span> &#123;</span><br><span class="line">	index := <span class="number">-1</span></span><br><span class="line">	<span class="keyword">for</span> i, x := <span class="keyword">range</span> arr &#123;</span><br><span class="line">		<span class="keyword">if</span> item == x &#123;</span><br><span class="line">			index = i</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> index &gt; <span class="number">-1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
                </div>
            </div>
    
            <nav class="post-pagination">
    
    <span class="page-number"></span>
    
    <a class="older-posts" href="/2020-04-07/Flutter开发日记-侧滑删除组件.html">
        Next post<br>Flutter开发日记-侧滑删除组件
    </a>
    
</nav>

    
            


        </div>
    </div>
    <div class="single-column-footer">
    Proudly published with Hexo<br>
    
    Theme <a href="https://github.com/SumiMakito/hexo-theme-journal/" target="_blank" rel="noreferrer noopener">Journal.</a> by <a href="https://mak1t0.cc/" target="_blank" rel="noreferrer noopener">Makito</a><br>
    
    &copy; 2020 <a href="https://sukeai.netlify.com">suke`s Notice</a>
</div>
</div>

</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.4/dist/umd/popper.min.js" integrity="sha256-EGs9T1xMHdvM1geM8jPpoo8EZ1V1VRsmcJz8OByENLA=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/js/bootstrap.min.js" integrity="sha256-VsEqElsCHSGmnmHXGQzvoWjWwoznFSZc6hs7ARLRacQ=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js" integrity="sha256-FtWfRI+thWlNz2sB3SJbwKx5PgMyKIVgwHCTwa3biXc=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/smooth-scroll@14.2.1/dist/smooth-scroll.polyfills.min.js" integrity="sha256-CI4Gq5E0io1Pv0xM3qPM+NUIOhbIBvC3GiN1Y4KhXpw=" crossorigin="anonymous"></script>
<script src="/js/journal.js?97840756"></script>



</body>
</html>
